/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.modules.sys.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.persistence.Page;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.modules.sys.entity.Company;
import cn.net.ecode.modules.sys.entity.Employee;
import cn.net.ecode.modules.sys.entity.Office;
import cn.net.ecode.modules.sys.entity.Role;
import cn.net.ecode.modules.sys.entity.User;
import cn.net.ecode.modules.sys.service.CompanyService;
import cn.net.ecode.modules.sys.service.OfficeService;
import cn.net.ecode.modules.sys.service.RoleService;
import cn.net.ecode.modules.sys.service.SecAdminUserService;
import cn.net.ecode.modules.sys.service.UserService;
import cn.net.ecode.modules.sys.utils.UserUtils;

/**
 * 二级管理员Controller
 * @author liubaoquan、ThinkGem
 * @version 2014-8-19
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/secAdminUser")
public class SecAdminUserController extends BaseController {

	@Autowired
	private SecAdminUserService secAdminUserService;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private OfficeService officeService;

	@ModelAttribute
	public User get(String userCode, boolean isNewRecord) {
		return userService.get(userCode, isNewRecord);
	}
	
	@RequiresPermissions("sys:secAdminUser:view")
	@RequestMapping(value = {"list", ""})
	public String list(User user, Model model) {
		return "modules/sys/secAdminUserList";
	}

	@RequiresPermissions("sys:secAdminUser:view")
	@ResponseBody
	@RequestMapping(value = "listData")
	public Page<User> listData(User user, HttpServletRequest request, HttpServletResponse response) {
		user.setUserType(User.USER_TYPE_EMPLOYEE); 	// 员工
		user.setMgrType(User.MGR_TYPE_SEC_ADMIN);	// 二级管理员
		Page<User> page = userService.findPage(new Page<User>(request, response), user);
		return page;
	}

	@RequiresPermissions("sys:secAdminUser:view")
	@RequestMapping(value = "form")
	public String form(User user, HttpServletRequest request, Model model) {
		
		String op = request.getParameter("op");
		
		// 获取当前编辑用的角色和权限
		if(op.equals("authorize")) {
			user.setRoleList(secAdminUserService.findUserRoleList(user));
			user.setUserDataScopeList(secAdminUserService.findUserDataScopeList(user));
		}
		
		// 获取可分配的权限
		model.addAttribute("allRoles", roleService.findList(new Role()));
		model.addAttribute("allCompanys", companyService.findList(new Company()));
		model.addAttribute("allOffices", officeService.findList(new Office()));
		
		// 获取编辑用户引用类型数据
		UserUtils.loadRefObj(user);
		user.setEmployee((Employee)user.getRefObj());
		model.addAttribute("secAdminUser", user);
		return "modules/sys/secAdminUserForm";
	}

	@RequiresPermissions("sys:secAdminUser:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(User user, HttpServletRequest request) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		if (User.isAdmin(user.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		StringBuilder message = new StringBuilder();
		if (!beanValidator(message, user)) {
			return renderResult(Global.FALSE, message);
		}
//		if (!"true".equals(checkUserCode(user.getOldUserCode(), user.getUserCode()))) {
//			return renderResult(Global.FALSE, "保存二级管理员'" + user.getUserCode() + "'失败，二级管理员已存在");
//		}
		String op = request.getParameter("op");
		// 用户授权操作
		if (op.equals("authorize")) {
			secAdminUserService.saveAuthorize(user);
		}
		// 编辑用户操作
		else if (op.equals("edit")) {
			secAdminUserService.editUser(user);
		}
		// 添加用户操作
		else if (op.equals("add")) {
			secAdminUserService.addUser(user);
		}
		// 如果修改的是当前用户，则清除当前用户缓存
		if (user.getUserCode().equals(UserUtils.getUser().getUserCode())) {
			UserUtils.clearCache();
		}
		return renderResult(Global.TRUE, "保存二级管理员'" + user.getUserCode() + "'成功");
	}

	/**
	 * 验证登录名是否有效
	 * @param oldUserCode
	 * @param userCode
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "checkUserCode")
	public String checkUserCode(String oldUserCode, String userCode) {
		if (userCode != null && userCode.equals(oldUserCode)) {
			return "true";
		} else if (userCode != null && userService.get(userCode) == null) {
			return "true";
		}
		return "false";
	}
	
	/**
	 * 停用二级管理员
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:secAdminUser:disable")
	@RequestMapping(value = "disable")
	public String disable(User user) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		String message = "";
		if (UserUtils.getUser().getId().equals(user.getId())) {
			message = "停用二级管理员失败, 不允许停用当前二级管理员";
		} else {
			userService.disableUser(user);
			message = "停用二级管理员成功";
		}
		return renderResult(Global.TRUE, message);
	}

	/**
	 * 启用二级管理员
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:secAdminUser:activate")
	@RequestMapping(value = "activate")
	public String activate(User user) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		userService.activateUser(user);
		return renderResult(Global.TRUE, "启用二级管理员成功");
	}

	/**
	 * 解冻二级管理员
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:secAdminUser:unfreeze")
	@RequestMapping(value = "unfreeze")
	public String unfreeze(User user) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		userService.activateUser(user);
		return renderResult(Global.TRUE, "解冻二级管理员成功");
	}

	/**
	 * 密码重置
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:secAdminUser:resetpwd")
	@RequestMapping(value = "resetpwd")
	public String resetpwd(User user) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		userService.resetUserPassword(user);
		return renderResult(Global.TRUE, "重置二级管理员密码成功");
	}

}
